<template>
  <el-select
    style="width: 100%"
    :multiple="ui.multiple"
    :collapseTags="ui.collapseTags"
    :maxCollapseTags="ui.maxCollapseTags"
    :clearable="ui.clearable"
    :multipleLimit="ui.multipleLimit"
    :placeholder="ui.placeholder"
    :disabled="ui.disabled"
    :size="ui.size"
    :valueKey="ui.valueKey"
    :remote="ui.remote"
    :remoteMethod="remoteMethod"
    :filterable="ui.remote"
    :reserve-keyword="ui.remote"
    :loading="loading"
    :modelValue="val"
    @update:model-value="updateValue"
  >
    <template v-if="ui.enabledGroup">
      <el-option-group
        v-for="group in items"
        :key="group.label"
        :label="group.label"
      >
        <template v-for="(item, i) in group.options" :key="i">
          <el-option
            v-if="!item.hidden"
            :label="item.label"
            :value="item.value"
            :disabled="item.disabled"
          />
        </template>
      </el-option-group>
    </template>
    <template v-else>
      <template v-for="(item, i) in items" :key="i">
        <el-option
          v-if="!item.hidden"
          :label="item.label"
          :value="item.value"
          :disabled="item.disabled"
        />
      </template>
    </template>
  </el-select>
</template>
<script lang="ts" setup name="lc-sf-select">
import { asyncComputed } from "@vueuse/core";
import { inject, ref, computed } from "vue";
import { SelectUI } from "../interface";
import { SFService } from "../sf.service";
import { NzSafeAny, TItemOption } from "../type";
const props = defineProps<TItemOption<SelectUI>>();
const loading = ref(false);
const ui = props.service.getUI<SelectUI>();
/** 根据枚举值的类型动态赋予双向绑定参数格式 */
const sf = inject<SFService>("sf-service");
const val = computed(() => {
  return sf.getVaule(props.keyPath);
});
/** 判断是否需要赋值非搜索数据 */
const items = !ui.remote
  ? asyncComputed<NzSafeAny>(async () => {
      if (typeof ui.items === "function") {
        if (ui.items instanceof Promise) {
          return (await ui.items()) || [];
        }
        return ui.items() || [];
      }
      return ui.items;
    })
  : ref([]);

/** 远程搜索回调函数 */
const remoteMethod = (query: string) => {
  if (ui.remote && ui.remoteMethod) {
    loading.value = true;
    const result = ui.remoteMethod(query);
    props.service.setUI("items", result as NzSafeAny);
  }
};
/** 同步双向绑定参数更新 */
const updateValue = (val: string | Record<string, NzSafeAny>) => {
  if (ui.change) {
    ui.change(val);
  }
  sf.setVaule(props.keyPath, val);
};
</script>

<style />
../types
